package com.devshephard.jucks.pc;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class lockNotify {

    public static void main(String[] args) {

        Data3 data3 = new Data3();

        new Thread(()->{

            try{
                for (int i = 0; i < 10; i++) {
                    data3.printA();
                }
            }catch (Exception e){
                e.printStackTrace();
            }
        },"A").start();

        new Thread(()->{
            try{
                for (int i = 0; i < 10; i++) {
                    data3.printB();
                }
            }catch (Exception e){
                e.printStackTrace();
            }
        },"B").start();

        new Thread(()->{

            try{
                for (int i = 0; i < 10; i++) {
                    data3.printC();
                }
            }catch (Exception e){
                e.printStackTrace();
            }

        },"C").start();

    }

}


class Data3{

    private Integer number = 1;

    private Lock lock = new ReentrantLock();

    Condition condition1 = lock.newCondition();
    Condition condition2 = lock.newCondition();
    Condition condition3 = lock.newCondition();

    public void printA() throws InterruptedException {

        lock.lock();

        try{

            while (number != 1){
                condition1.await();
            }
            number = 2;
            System.out.println(Thread.currentThread().getName() + "=>" + "AAAAAAAA");
            condition2.signal();

        }catch (Exception e){
            e.printStackTrace();
        }finally {
            lock.unlock();
        }


    }

    public void printB(){

        lock.lock();

        try{
            while (number != 2){
                condition2.await();
            }
            number = 3;
            System.out.println(Thread.currentThread().getName() + "=>" + "BBBBBBBB");
            condition3.signal();

        }catch (Exception e){
            e.printStackTrace();
        }finally {
            lock.unlock();
        }

    }

    public void printC(){

        lock.lock();

        try{
            while (number != 3){
                condition3.await();
            }
            number = 1;
            System.out.println(Thread.currentThread().getName() + "=>" + "CCCCCCCC");
            condition1.signal();

        }catch (Exception e){
            e.printStackTrace();
        }finally {
            lock.unlock();
        }

    }
}